<template>
  <div class="code-parse-rule-detail">
    <!-- <g-detail ref="detail" :inputConfig="inputConfig" :rules="rules" @changeDetail="changeDetail" ></g-detail> -->
    <el-form :rules="rules" ref="form" :model="inputData" inline label-width="80px"
      >
      <el-form-item :label="$t('transmit.ruleNo')" prop="ruleNo">
        <el-input v-model="inputData.ruleNo"></el-input>
      </el-form-item>
      <el-form-item :label="$t('transmit.ruleName')" prop="ruleName">
        <el-input v-model="inputData.ruleName"></el-input>
      </el-form-item>
      <el-form-item :label="$t('transmit.validTime')" prop="validTime">
        <el-date-picker v-model="inputData.validTime" type="datetimerange" :picker-options="pickerOptions1"
          range-separator="-" :start-placeholder="$t('app.startDate')" :end-placeholder="$t('app.endDate')"
          align="right"> </el-date-picker>
      </el-form-item>
      <br />
      <template v-if="invalid != 'parse'">
        <el-form-item :label="$t('transmit.readRuleType')" prop="readRuleType">
          <el-select v-model="inputData.readRuleType" @change="handleRuleType">
            <el-option v-for="opt in getOptions('codelkup/ReadRuleType')" :key="opt.code" :value="opt.code"
              :label="opt.description"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('transmit.ruleObjectNo')" prop="ruleObjectNo">
          <el-select v-model="inputData.ruleObjectNo" @change="handleRuleObj">
            <el-option value="" label=""></el-option>
            <el-option v-for="opt in ruleObjectList" :key="opt.storerkey" :value="opt.storerkey"
              :label="opt.storerkey"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('transmit.ruleObjectName')" prop="ruleObjectName">
          <el-input v-model="inputData.ruleObjectName" disabled></el-input>
        </el-form-item>
      </template>
      <el-form-item :label="$t('transmit.dataLength')">
        <el-input v-model="inputData.dataLength" disabled></el-input>
      </el-form-item>
    </el-form>
    <div v-if="invalid == 'parse'">
      <p>{{ $t('transmit.dataLength') }}</p>
      <div class="lr-layout">
        <el-input ref="parseInput" class="left-wrap" type="textarea" :rows="6" placeholder="" v-model="checkStr">
        </el-input>
        <el-button class="right-wrap" type="primary" @click="handleParse">{{ $t('transmit.parse1') }}</el-button>
      </div>
    </div>
    <template v-if="invalid == 'parse'">
      <p class="result-label">{{ $t('transmit.parseresult') }}</p>
      <el-table stripe border :data="list" v-loading="loading">
        <el-table-column type="index" :label="$t('app.index')" width="55" align="center"></el-table-column>
        <el-table-column v-for="column in columnSource" :key="column.prop" v-bind="column" align="center">
          <template slot-scope="{row,column,$index}">
            <template v-if="column.property == 'checkCode'">
              <span :style="{ color: row.checkCode == 'S' ? '#accd7c' : '#d25655' }">{{
                row.checkCode == 'S' ? '成功' : '失败'
              }}</span>
            </template>
            <template v-else-if="column.property == 'dataObject'">
              <span>{{ getLabel(row.dataObject, options.dataObject, 'description') }}</span>
            </template>
            <template v-else-if="column.property == 'dataType'">
              <span>{{ getLabel(row.dataType, options.dataType, 'description') }}</span>
            </template>
            <template v-else>
              <span>{{ row[column.property]}}</span>
            </template>
          </template>
        </el-table-column>
      </el-table>
    </template>
    <template v-else>
      <p class="result-label">{{ $t('transmit.parseruledetail') }}</p>
      <el-table stripe border :data="ruleInfoList" v-loading="loading" :max-height="calcHeight(150)">
        <el-table-column v-for="column in infoColumns" :key="column.prop" v-bind="column" align="center"
          :width="column.width">
          <template slot-scope="{column,$index,row}">
            <template v-if="['dataObject', 'dataType', 'qrSplitType'].includes(column.property)">
              <el-select v-model="ruleInfoList[$index][column.property]">
                <el-option value="" label=""></el-option>
                <el-option v-for="opt in options[column.property]" :key="opt.code" :value="opt.code"
                  :label="opt.description"></el-option>
              </el-select>
            </template>
            <template v-else-if="['startPosition', 'endPosition'].includes(column.property)">
              <el-input-number v-model="ruleInfoList[$index][column.property]" :min="1"></el-input-number>
            </template>
            <template v-else-if="['splitSortNum'].includes(column.property)">
              <el-input-number v-model="ruleInfoList[$index][column.property]" :min="1"
                :disabled="row.qrSplitType == '13001'"></el-input-number>
            </template>
            <template v-else-if="['splitChar'].includes(column.property)">
              <el-input v-model="ruleInfoList[$index][column.property]"
                :disabled="row.qrSplitType == '13001'"></el-input>
            </template>
            <template v-else-if="['forFixedValue'].includes(column.property)">
              <el-switch v-model="ruleInfoList[$index][column.property]" active-value="1" inactive-value="0">
              </el-switch>
            </template>
            <template v-else-if="['fixedValue'].includes(column.property)">
              <el-input v-model="ruleInfoList[$index][column.property]" :disabled="row.forFixedValue == '0'"></el-input>
            </template>
            <template v-else-if="['readLength'].includes(column.property)">
              <span>{{ getReadLength(column, $index) }}</span>
            </template>
            <template v-else>
              <span>{{ $index + 1}}</span>
            </template>
          </template>
        </el-table-column>
        <el-table-column :label="$t('transmit.action')" align="center">
          <template slot-scope="scope">
            <el-button type="text" @click="handleAddRuleInfo(scope)">{{ $t('common.add') }}</el-button>
            <el-button type="text" @click="handleDelRuleInfo(scope)"
              v-if="scope.$index != 0">{{ $t("common.delete") }}</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>
  </div>
</template>

<script>
import baseMixin from "@/mixins/BaseMixin";
import { mapGetters } from "vuex";
export default {
  name: "Detail",
  mixins: [baseMixin],
  props: {
    invalid: { type: String }
  },
  data() {
    return {
      newFlag: true,
      checkStr: "",
      inputData: {
        ruleNo: "",
        ruleName: "",
        validTime: [],
        readRuleType: "",
        ruleObjectNo: "",
        ruleObjectName: "",
        dataLength: ''
      },
      ruleList: [],
      ruleObjectList: [],
      pickerOptions1: {
        shortcuts: [{
          text: this.$t('app.nextweek'),
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() + 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: this.$t('app.nextmonth'),
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() + 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: this.$t('app.nextquarter'),
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() + 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      rules: {
        ruleNo: [{ required: true, message: this.$inputPlease('transmit.ruleNo'), trigger: "blur" },],
        ruleName: [{ required: true, message: this.$inputPlease('transmit.ruleName'), trigger: "blur" },],
        validTime: [{ required: true, message: this.$selectPlease('transmit.validTime'), trigger: "blur" },],
        readRuleType: [{ required: true, message: this.$selectPlease('transmit.readRuleType'), trigger: "blur" },],
        ruleObjectNo: [{ required: true, message: this.$inputPlease('transmit.ruleObjectNo'), trigger: "blur" },],
        ruleObjectName: [{ required: true, message: this.$inputPlease('transmit.ruleObjectName'), trigger: "blur" },],
      },
      loading: false,
      ruleInfoList: [{ number: 1, dataObject: "", dataType: "", startPosition: 1, endPosition: 1, readLength: 1, forFixedValue: '0', fixedValue: "", qrSplitType: "13001", splitChar: "", splitSortNum: "" }],
      list: [],
      columnSource: [
        { label: this.$t('transmit.dataObject'), prop: "dataObject" },
        { label: this.$t('transmit.dataType'), prop: "dataType" },
        { label: this.$t('transmit.dataObject'), prop: "checkStr" },
        { label: this.$t('transmit.dataObject'), prop: "checkCode" },
        // {label:"解析状态",prop:""},
        { label: this.$t('transmit.dataObject'), prop: "checkMsg" },
      ],
      infoColumns: [
        { label: this.$t('app.index'), prop: "number", width: 50 },
        { label: this.$t('transmit.dataObject'), prop: "dataObject", width: 80 },
        { label: this.$t('transmit.dataType'), prop: "dataType", width: 100 },
        { label: this.$t('transmit.qrSplitType'), prop: "qrSplitType", width: 120 },
        { label: this.$t('transmit.splitChar'), prop: "splitChar", width: 100 },
        { label: this.$t('transmit.splitSortNum'), prop: "splitSortNum", width: 100 },
        { label: this.$t('transmit.startPosition'), prop: "startPosition", width: 100 },
        { label: this.$t('transmit.endPosition'), prop: "endPosition", width: 100 },
        { label: this.$t('transmit.readLength'), prop: "readLength", width: 70 },
        { label: this.$t('transmit.forFixedValue'), prop: "forFixedValue", width: 80 },
        { label: this.$t('transmit.fixedValue'), prop: "fixedValue", width: 100 },
      ],
      options: {
        dataObject: [],
        dataType: [],
        qrSplitType: []
      }
    };
  },
  computed: {
    ...mapGetters(['routeData']),

  },
  watch: {
    routeData: {
      handler(nv, ov) {
        if (nv.id != ov.id) {
          this.init()
        }
      },
      deep: true
    },
    invalid: {
      handler(nv) {
        if (nv == 'parse') {
          this.$nextTick(() => {
            this.$refs.parseInput.focus()
          })
        }
      },
      immediate: true
    }
  },
  methods: {
    submit() {
      let validStatus = false;
      this.$refs.form.validate(valid => validStatus = valid)
      if (validStatus) {
        this.inputData.dataLength = this.ruleInfoList.reduce((pre, cur) => pre + cur.readLength, 0)
        let params = this._.cloneDeep(this.inputData);
        params.detailList = this.ruleInfoList;
        params.validTime = this.inputData.validTime[0];
        params.invalidTime = this.inputData.validTime[1];
        if (this.newFlag) {
          return this.$post("/baBarcodeReadRule/insert", params).then(res => {
              this.$message.success(this.$t('app.addMes'));
              return Promise.resolve(res)
          })
        } else {
          params = { ...this.routeData, ...params };
          return this.$post("/baBarcodeReadRule/update", params).then(res => {
              this.$message.success(this.$t('app.upMes'));
              return Promise.resolve(res)
          })
        }
      }
      return Promise.reject()
    },
    getLabel(val, list, key) {
      const obj = list.find(item => item.code == val)
      return obj ? obj[key] : null
    },
    getReadLength(column, $index) {
      const data = this.ruleInfoList[$index];
      if (data.startPosition && data.endPosition) {
        const len = data.endPosition - data.startPosition + 1;
        this.ruleInfoList[$index].readLength = len;
        return len
      }
    },
    handleAddRuleInfo(scope) {
      const index = scope.$index;
      this.ruleInfoList.splice(index + 1, 0, { number: 1, dataObject: "", dataType: "", startPosition: 1, endPosition: 1, readLength: 1, forFixedValue: '0', fixedValue: "", qrSplitType: "13001", splitChar: "", splitSortNum: "" })
    },
    handleDelRuleInfo(scope) {
      const index = scope.$index;
      this.ruleInfoList.splice(index, 1)
    },
    handleRuleType(type) {
      console.log(type);
      if (['12302', '12303'].includes(type)) {
        this.$message(this.$t('msg.msg82'))
      }
    },
    handleRuleObj(storerkey) {
      const obj = this.ruleObjectList.find(item => item.storerkey == storerkey);
      this.inputData.ruleObjectName = obj.company;
      this.inputData.ruleObjectId = obj.serialkey;
    },
    getRuleObjectList() {
      this.$post("/queryStorer/1/1/enterprise", {}).then(res => {
        this.ruleObjectList = res.page.list;
      })
      this.$get("/codeLookup/ReadRuleDataObject").then(res => {
        this.options.dataObject = res.list;
      })
      this.$get("/codeLookup/ReadRuleDataType").then(res => {
        this.options.dataType = res.list;
      })
      this.$get("/codeLookup/QrSplitType").then(res => {
        this.options.qrSplitType = res.list;
      })
    },
    handleParse() {
      let params = { id: this.routeData.id };
      params.checkStr = this.checkStr;
      this.loading = true;
      this.$post("/baBarcodeReadRule/verifyBaBarcodeReadRule", params).then(res => {
        this.list = res.data
      }).finally(() => {
        this.loading = false;
      })
    },
    getRuleInfoById() {
      let id = this.routeData.id;
      this.$get(`/baBarcodeReadRule/queryById/${id}`).then(res => {
        this.ruleInfoList = res.data.detailList
      })
    },
    init() {
      //判断是否事新建
      console.log(this.invalid);
      if (this.invalid == 'detail') {
        this.newFlag = false;
        this.getRuleInfoById()
        this.inputData = { ...this.inputData, ...this.routeData };
        this.inputData.validTime = this.routeData.validTime && this.routeData.invalidTime ? [new Date(this.routeData.validTime), new Date(this.routeData.invalidTime)] : [];
      } else if (this.invalid == 'copy' || this.invalid == 'newCreate') {
        this.newFlag = true;
        if (this.invalid == 'copy') {
          this.getRuleInfoById()
          this.inputData = { ...this.inputData, ...this.routeData };
          this.inputData.validTime = this.routeData.validTime && this.routeData.invalidTime ? [new Date(this.routeData.validTime), new Date(this.routeData.invalidTime)] : [];
        } else {
          this.inputData = { ruleNo: "", ruleName: "", validTime: [], readRuleType: "", ruleObjectNo: "", ruleObjectName: "", dataLength: '' }
          this.ruleInfoList = [{ number: 1, dataObject: "", dataType: "", startPosition: 0, endPosition: 0, readLength: 0, forFixedValue: '0', fixedValue: "", qrSplitType: "13001", splitChar: "", splitSortNum: "" }]
        }
      } else {
        this.inputData = { ...this.inputData, ...this.routeData };
        this.inputData.validTime = this.routeData.validTime && this.routeData.invalidTime ? [new Date(this.routeData.validTime), new Date(this.routeData.invalidTime)] : [];
      }
    },
  },
  mounted() {
    this.init()
    this.getRuleObjectList()
  },
  components: {},
};
</script>

<style lang="scss" scoped>
.code-parse-rule-detail {
  padding: 10px;

  .result-label {
    margin-top: 1em;
  }

  .el-input,
  .el-select {
    width: 160px;
    /*min-height: 50px;*/
    margin-right: 16px;
  }

  .el-date-editor--datetimerange {
    width: 380px;
    margin-right: 16px;
  }

  ::v-deep .el-date-editor .el-range-separator {
    line-height: 100%;
  }

  .el-table {
    :deep .el-table__header-wrapper {
      .el-table__cell {
        background: #f1f2f3;
      }
    }

    .el-input,
    .el-select {
      width: 100%;
      /*min-height: 50px;*/
      margin-right: 0;
    }

    .el-input-number {
      width: 100%;
      line-height: 22px;

      ::v-deep .el-input-number__decrease {
        width: 20px;
      }

      ::v-deep .el-input-number__increase {
        width: 20px;

      }

      ::v-deep .el-input__inner {
        padding-left: 30px;
        padding-right: 30px;
      }
    }

    .el-button {
      width: 40px;
    }
  }
}
</style>
